import {
  generateCrudPage,
  headerToolbar,
  bulkActions,
  listButtons,
} from "./sys_columns.ts";
import  {parse}  from "url";
import adminCrud from "./sys_admin_crud.ts";
import AdminPermissions from "../models/AdminPermissions.ts";
import AdminRoles from "../models/AdminRoles.ts";
import AdminRolePermissions  from "../models/AdminRolePermissions.ts";
import { successResponse, errorResponse } from "../../helpers.ts";
const apiUrl = "/admin-api/system/admin_roles";

export async function grid() {
  const list = {
    apiUrl: apiUrl,
    headerToolbar: await headerToolbar(apiUrl, form), //头部工具栏
    bulkActions: await bulkActions(), //批量操作
    filter: await filter(), //筛选
    itemCheckableOn: "this.id != 1",
    columns: [
      { name: "id", label: "ID" },
      { name: "name", label: "名称" },
      { name: "slug", label: "标识" },
      { name: "created_at", label: "创建时间" },
      { name: "updated_at", label: "保存时间" },
      await listButtons({
        types: ["button1", "edit", "detail", "delete"],
        apiUrl: apiUrl,
        detail: detail,
        form: form,
        button1: button1,
      }),
    ],
  };
  return await generateCrudPage(list);
}

//表单配置
async function form() {
  return [
    { type: "input-text", name: "name", label: "名称", required: true },
    { type: "input-text", name: "slug", label: "标识", required: true },
  ];
}

//详情配置
async function detail() {
  return {
    title: "查看详情",
    body: {
      type: "form",
      body: [
        {
          type: "input-text",
          name: "name",
          label: "名称",
          value: "${name}",
          disabled: true,
        },
        {
          type: "input-text",
          name: "slug",
          label: "标识",
          value: "${slug}",
          disabled: true,
        },
      ],
    },
  };
}

//筛选配置
async function filter() {
  return {
    title: "筛选",
    mode: "inline",
    controls: [
      { type: "input-text", name: "name", label: "名称" },
      { type: "submit", label: "查询", level: "primary" },
      { type: "reset", label: "重置" },
    ],
  };
}

async function button1() {
  return {
    type: "button",
    actionType: "drawer",
    label: "设置权限",
    level: "link",
    drawer: {
      type: "drawer",
      title: "设置权限",
      resizable: true,
      closeOnOutside: true,
      closeOnEsc: true,
      body: [
        {
          type: "form",
          api: "/admin-api/system/admin_roles?_action=save_permissions",
          initApi:
            "/admin-api/system/admin_roles/${id}/edit?_action=get_permissionss",
          mode: "normal",
          data: {
            id: "${id}",
          },
          body: [
            {
              type: "input-tree",
              name: "permissions",
              label: "",
              multiple: true,
              heightAuto: true,
              options: await getPermissionsTreeOptions2(), //设置权限
              searchable: true,
              cascade: true,
              joinValues: false,
              extractValue: true,
              size: "full",
              className: "h-full b-none",
              inputClassName: "h-full tree-full",
              labelField: "name",
              valueField: "id",
            },
          ],
        },
      ],
    },
  };
}

export const SysRolesController = {
  async index(req, res) {
    const queryParams = parse(req.url, true).query;
    if (queryParams._replace === "1") {
      const list = await grid();
      return successResponse(res, {data: list});
    }
    try {
      const query = AdminRoles.query();
      if (req.query.name) {
        query.where("name", "like", `%${req.query.name}%`);
      }
      const list = await query.paginate(req.query.page, req.query.perPage);
      return successResponse(res, {data: list.items()});
    } catch (error) {
      console.error("获取角色列表失败:", error);
      return errorResponse(res, {msg: "服务器错误，请稍后重试"});
    }
  },

  async store(req, res) {
    const query = require("url").parse(req.url, true).query;
    if (query._action === "save_permissions") {
      const { id, permissions } = req.body;
      if (!id || !permissions) {
        return errorResponse(res, {msg: "无效的请求参数！"});
      }
      try {
        await AdminRolePermissions.query().where({ role_id: id }).delete();

        if (permissions.length > 0) {
          const now = new Date();
          const data = permissions.map((item) => {
            const permission_id = typeof item === "object" ? item.id : item;
            return {
              role_id: id,
              permission_id,
              created_at: now,
              updated_at: now,
            };
          });

          await AdminRolePermissions.query().insert(data);
        }

        return successResponse(res, {msg: "保存成功！"});
      } catch (error) {
        console.error(error);
        return errorResponse(res, {msg: "服务器错误！"});
      }
    }

    return adminCrud.store(req, res, AdminRoles);
  },

  async edit(req, res) {
    const { id } = req.params;
    if (!id) {
      return errorResponse(res, {msg: "无效的请求参数！"});
    }
    const query = require("url").parse(req.url, true).query;
    if (query._action === "getData") {
      const roles = await AdminRoles.query().find(id);
      return successResponse(res, {data: roles});
    }
    if (query._action === "get_permissionss") {
      try {
        const roles = await AdminRoles.query().with("permissions").find(id);
        const responseData = {
          status: 0,
          msg: "ok",
          data: roles,
        };
        return successResponse(res, {data: roles});
      } catch (error) {
        return errorResponse(res, {msg: "服务器错误！" + error});
      }
    }
  },

  async update(req, res) {
    const { id } = req.params;
    const params = req.body;
    if (!id || !params || Object.keys(params).length === 0)
      return errorResponse(res, {msg: "无效的请求参数！"});
    try {
      delete params.updated_at;
      delete params.created_at;
      const result = await AdminRoles.query().where({ id }).update(params);
      return successResponse(res, {msg: result ? "保存成功！" : "保存失败！"});
    } catch (error) {
      console.error("数据库错误：", error);
      return errorResponse(res, {msg: "服务器错误！"});
    }
  },

  async destroy(req, res) {
    return adminCrud.destroy(req, res, AdminRoles);
  },
};

//获取权限树
export async function getPermissionsTreeOptions2() {
  const menus = await AdminPermissions.query()
    .orderBy("custom_order", "asc")
    .get();
  const list = menus.toJSON();

  const map = {};
  const tree = [];

  // 先将所有节点初始化到map里
  list.forEach((item) => {
    map[item.id] = {
      ...item,
      children: [],
    };
  });

  // 再遍历所有节点，挂到对应父节点下
  list.forEach((item) => {
    if (item.parent_id && map[item.parent_id]) {
      map[item.parent_id].children.push(map[item.id]);
    } else {
      // 没有父级或parent_id=0，直接作为顶级节点放入tree
      tree.push(map[item.id]);
    }
  });

  return tree;
}
